package com.fenghongzhang.day011;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;

public class MainActivity extends AppCompatActivity {
    private Button readCon;

    private static final String TAG = "MainActivity";
    private ContentResolver contentResolver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        readCon = (Button) findViewById(R.id.readCon);


        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS,Manifest.permission.WRITE_CONTACTS},999);

         contentResolver = getContentResolver();


//         new FileOutputStream(new File(?,"dd.txt"));



        readCon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor query = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
                if (query != null){
                    while(query.moveToNext()){
                        String name = query.getString(query.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String number = query.getString(query.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Toast.makeText(MainActivity.this, name+":"+number, Toast.LENGTH_SHORT).show();

                        //保存数据
                        test();
                        //存到数据库中

                    }

                }
            }
        });

    }

    public void test(){
        Log.i(TAG, "test: ");
        //10
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 999 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

        }else{
            finish();
        }
    }
}
